// static/js/schedule_modify.js

;(function(){
  document.addEventListener('DOMContentLoaded', () => {
    // Detail modal elements
    const detailModalEl   = document.getElementById('scheduleDetailModal');
    const detailError     = document.getElementById('detailErrorMsg');
    const modifyBtn       = document.getElementById('detail-modify');
    const modifyOptions   = document.getElementById('modify-options');
    const optOnceMod      = document.getElementById('opt-modify-once');
    const optOngoingMod   = document.getElementById('opt-modify-ongoing');

    // Once-modify modal elements
    const onceModalEl     = document.getElementById('modifyOnceModal');
    const onceForm        = document.getElementById('modify-once-form');
    const errorOnce       = document.getElementById('modifyOnceError');

    // Ongoing-modify modal elements
    const ongoingModalEl  = document.getElementById('modifyOngoingModal');
    const ongoingForm     = document.getElementById('modify-ongoing-form');
    const errorOngoing    = document.getElementById('modifyOngoingError');

    let currentData       = null;
    let currentId         = null;

    // Utility: hide modify-options panel
    function hideModifyOptions() {
      modifyOptions.style.display = 'none';
    }

    // When detail modal opens, sync currentData and hide options/errors
    detailModalEl.addEventListener('show.bs.modal', () => {
      hideModifyOptions();
      detailError.style.display = 'none';
      currentData = window.currentData || null;
      currentId   = currentData ? currentData.id : null;
    });

    // Clicking outside hides panel
    document.addEventListener('click', () => {
      hideModifyOptions();
    });

    // Toggle modify-options panel
    modifyBtn.addEventListener('click', e => {
      e.stopPropagation();
      hideModifyOptions();
      modifyOptions.style.display = modifyOptions.style.display === 'flex' ? 'none' : 'flex';
    });
    modifyOptions.addEventListener('click', e => e.stopPropagation());

    // Fetch metadata for selects
    async function fetchMetadata(form) {
      const [courses, schools, grades] = await Promise.all([
        fetch('/api/courses').then(r => r.json()),
        fetch('/api/schools').then(r => r.json()),
        fetch('/api/grades').then(r => r.json())
      ]);
      fillSelect(form.course, courses);
      fillSelect(form.school, schools);
      fillSelect(form.grade, grades);
    }
    function fillSelect(sel, list) {
      sel.innerHTML = '<option value="" disabled>请选择</option>';
      list.forEach(x => sel.add(new Option(x.name, x.name)));
    }

    // Fill once-form fields
    function fillOnceForm() {
      const f = onceForm;
      f.student_name.value = currentData.student_name;
      f.course.value       = currentData.course;
      f.school.value       = currentData.school;
      f.grade.value        = currentData.grade;
      f.address.value      = currentData.address;
      f.fee.value          = currentData.fee;
      f.one_date.value     = currentData.date;
      f.start_time.value   = currentData.start_time;
      f.end_time.value     = currentData.end_time;
      f.remark.value       = currentData.remark;
    }

    // Fill ongoing-form fields
    function fillOngoingForm() {
      const f = ongoingForm;
      f.student_name.value = currentData.student_name;
      f.course.value       = currentData.course;
      f.school.value       = currentData.school;
      f.grade.value        = currentData.grade;
      f.address.value      = currentData.address;
      f.fee.value          = currentData.fee;
      // default start_date as currentData.date
      f.start_date.value   = currentData.date;
      f.end_date.value     = currentData.end_date;
      f.start_time.value   = currentData.start_time;
      f.end_time.value     = currentData.end_time;
      f.remark.value       = currentData.remark;
      // clear all weekdays then set
      ongoingForm.querySelectorAll('input[name="weekdays"]').forEach(cb => cb.checked = false);
      (currentData.weekdays || []).forEach(d => {
        const cb = ongoingForm.querySelector(`input[name="weekdays"][value="${d}"]`);
        if (cb) cb.checked = true;
      });
    }

    // Handle click “本次修改”
    optOnceMod.addEventListener('click', () => {
      hideModifyOptions();
      if (!currentData || currentData.status === '已上') {
        detailError.textContent = currentData && currentData.status === '已上'
          ? '该排课已完成，无法修改本次。'
          : '请先选择一条排课记录。';
        detailError.style.display = 'inline';
        setTimeout(() => detailError.style.display = 'none', 3000);
        return;
      }
      errorOnce.style.display = 'none';
      fetchMetadata(onceForm).then(fillOnceForm);
      new bootstrap.Modal(onceModalEl).show();
    });

    // Handle click “本次及后续修改”
    optOngoingMod.addEventListener('click', () => {
      hideModifyOptions();
      if (!currentData || currentData.status === '已上') {
        detailError.textContent = currentData && currentData.status === '已上'
          ? '该排课已完成，无法修改本次及后续。'
          : '请先选择一条排课记录。';
        detailError.style.display = 'inline';
        setTimeout(() => detailError.style.display = 'none', 3000);
        return;
      }
      errorOngoing.style.display = 'none';
      fetchMetadata(ongoingForm).then(fillOngoingForm);
      new bootstrap.Modal(ongoingModalEl).show();
    });

    // Submit once-form via PUT /modify
    onceForm.addEventListener('submit', async e => {
      e.preventDefault();
      errorOnce.style.display = 'none';
      try {
        const payload = Object.fromEntries(new FormData(onceForm).entries());
        payload.type = 'once';
        const res = await fetch(`/api/schedules/${currentId}/modify`, {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(payload)
        });
        if (!res.ok) {
          const p = await res.json();
          throw new Error(p.error || p.message || '修改失败');
        }
        bootstrap.Modal.getInstance(onceModalEl).hide();
        bootstrap.Modal.getInstance(detailModalEl).hide();
        if (typeof loadCards === 'function') loadCards();
      } catch (err) {
        errorOnce.textContent = err.message;
        errorOnce.style.display = 'inline';
        setTimeout(() => errorOnce.style.display = 'none', 3000);
      }
    });

    // Submit ongoing-form via PUT /modify
    ongoingForm.addEventListener('submit', async e => {
      e.preventDefault();
      errorOngoing.style.display = 'none';
      try {
        const formData = new FormData(ongoingForm);
        const payload = Object.fromEntries(formData.entries());
        payload.weekdays = formData.getAll('weekdays');
        payload.type = 'weekly';
        const res = await fetch(`/api/schedules/${currentId}/modify`, {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(payload)
        });
        if (!res.ok) {
          const p = await res.json();
          throw new Error(p.error || p.message || '修改失败');
        }
        bootstrap.Modal.getInstance(ongoingModalEl).hide();
        bootstrap.Modal.getInstance(detailModalEl).hide();
        if (typeof loadCards === 'function') loadCards();
      } catch (err) {
        errorOngoing.textContent = err.message;
        errorOngoing.style.display = 'inline';
        setTimeout(() => errorOngoing.style.display = 'none', 3000);
      }
    });
  });
})();
